package com.zozo.guanli.web.action.peijian;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.zozo.guanli.constants.PeijianConts;
import com.zozo.guanli.service.peijian.PeijianService;
import com.zozo.guanli.util.Page;
import com.zozo.guanli.vo.Accessory;
import com.zozo.guanli.web.action.AbstractBaseAction;

public class PeijianAction extends AbstractBaseAction<Accessory> {

    private static final Logger logger = Logger.getLogger(PeijianAction.class);

    private Accessory entity;

    private Long id;

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    private final String[] status = { "备用", "上车", "下车", "检修", "报废" };

    @Autowired
    private PeijianService peijianService;

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    public Accessory getModel() {
        return entity;
    }

    public String login() {
        request.getSession().setAttribute("login", "start");
        return null;
    }

    /**
     * 性能查询页面
     * @return
     */
    public String indicator() {
        return "indicator";
    }

    public String exit() {
        request.getSession().setAttribute("login", "");
        return null;
    }

    /**
     * 资源操作页面
     * @return
     */
    public String resource() {
        return "resource";
    }

    @Override
    public String list() throws Exception {
        try {
            StringBuilder condition = new StringBuilder();
            String type = request.getParameter("stype");
            if (type != null && type.length() > 0) {
                condition.append(" and a.type like '%" + type + "%'");
            }

            String sname = request.getParameter("sname");
            if (sname != null && sname.length() > 0) {
                condition.append(" and a.name like '%" + sname + "%'");
            }
            String status = request.getParameter("sstatus");
            if (status != null && status.length() > 0) {
                condition.append(" and a.status =" + status);
            }

            Page<Accessory> page = new Page<Accessory>();
            page.setPageNo(Integer.valueOf(request.getParameter("iDisplayStart")) / Integer.valueOf(request.getParameter("iDisplayLength")) + 1);
            page.setPageSize(Integer.valueOf(request.getParameter("iDisplayLength")));
            Page<Accessory> aaData = peijianService.findByPage(page, condition.toString());

            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();

            for (Accessory acce : aaData.getRows()) {
                System.out.println(acce.toString());
                JSONObject obj = new JSONObject();
                obj.element("op", buildOp(acce));
                obj.element("id", acce.getId());
                obj.element("result", acce.getMtresult() == null ? "" : acce.getMtresult());
                obj.element("ondate", acce.getOndate() == null ? "" : sdf.format(acce.getOndate()));
                obj.element("downDate", acce.getDownDate() == null ? "" : sdf.format(acce.getDownDate()));
                obj.element("xiuc", acce.getXiuc() == null ? "" : acce.getXiuc());
                obj.element("name", acce.getName());
                obj.element("code", acce.getCode());
                obj.element("type", acce.getType());
                obj.element("vendor", acce.getVendor());
                obj.element("leave", acce.getLeavedate() == null ? "" : sdf.format(acce.getLeavedate()));
                obj.element("mt", acce.getMtdate() == null ? "" : sdf.format(acce.getMtdate()));
                obj.element("status", buildStatus(acce));
                obj.element("car", acce.getFitcar());
                obj.element("miles", acce.getMiles());
                obj.element("oper", acce.getOpperson());
                array.add(obj);
            }

            json.element("iTotalRecords", page.getTotal());
            json.element("iTotalDisplayRecords", page.getTotal());
            json.element("aaData", array);
            renderText(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 资源模型
     * @return
     * @throws Exception
     */
    public String reslist() throws Exception {
        try {
            StringBuilder condition = new StringBuilder();
            String type = request.getParameter("stype");
            if (type != null && type.length() > 0) {
                condition.append(" and a.type like '%" + type + "%'");
            }

            String sname = request.getParameter("sname");
            if (sname != null && sname.length() > 0) {
                condition.append(" and a.name like '%" + sname + "%'");
            }
            String status = request.getParameter("sstatus");
            if (status != null && status.length() > 0) {
                condition.append(" and a.status =" + status);
            }

            Page<Accessory> page = new Page<Accessory>();
            page.setPageNo(Integer.valueOf(request.getParameter("iDisplayStart")) / Integer.valueOf(request.getParameter("iDisplayLength")) + 1);
            page.setPageSize(Integer.valueOf(request.getParameter("iDisplayLength")));
            Page<Accessory> aaData = peijianService.findByPage(page, condition.toString());

            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();

            for (Accessory acce : aaData.getRows()) {
                StringBuilder sb = new StringBuilder();
                sb.append("<div style='width: 130px;align:center;'>");
                sb.append("&nbsp;&nbsp;<a class='probebutton' href='javascript:del(" + acce.getId() + ");'>修改</a>");
                sb.append("&nbsp;&nbsp;<a class='probebutton' href='javascript:del(" + acce.getId() + ");'>删除</a></div>");

                System.out.println(acce.toString());
                JSONObject obj = new JSONObject();
                obj.element("op", sb.toString());
                obj.element("id", acce.getId());
                obj.element("result", acce.getMtresult() == null ? "" : acce.getMtresult());
                obj.element("ondate", acce.getOndate() == null ? "" : sdf.format(acce.getOndate()));
                obj.element("downDate", acce.getDownDate() == null ? "" : sdf.format(acce.getDownDate()));
                obj.element("xiuc", acce.getXiuc() == null ? "" : acce.getXiuc());
                obj.element("name", acce.getName());
                obj.element("code", acce.getCode());
                obj.element("type", acce.getType());
                obj.element("vendor", acce.getVendor());
                obj.element("leave", acce.getLeavedate() == null ? "" : sdf.format(acce.getLeavedate()));
                obj.element("mt", acce.getMtdate() == null ? "" : sdf.format(acce.getMtdate()));
                obj.element("status", buildStatus(acce));
                obj.element("car", acce.getFitcar());
                obj.element("miles", acce.getMiles());
                obj.element("oper", acce.getOpperson());
                array.add(obj);
            }

            json.element("iTotalRecords", page.getTotal());
            json.element("iTotalDisplayRecords", page.getTotal());
            json.element("aaData", array);
            renderText(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 执行上车操作
     * @return
     */
    public String saveup() {
        try {
            Long id = Long.parseLong(request.getParameter("id"));
            String date = request.getParameter("update");

            Date ondate = (date == null || date.length() < 1) ? null : sdf.parse(date);
            String cartype = request.getParameter("cartype");
            String position = request.getParameter("position");
            String xiuc = request.getParameter("xiuc");

            entity = peijianService.get(id);
            entity.setStatus(PeijianConts.STATUS_ON);
            entity.setOndate(ondate);
            entity.setCartype(cartype);
            entity.setPosition(position);
            entity.setXiuc(xiuc);

            peijianService.save(entity);
            JSONObject json = new JSONObject();
            json.element("success", 1);
            renderText(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 执行下车操作
     * @return
     */
    public String savedown() {
        try {
            Long id = Long.parseLong(request.getParameter("id"));
            String date = request.getParameter("downdate");

            Date downDate = (date == null || date.length() < 1) ? null : sdf.parse(date);
            String miles = request.getParameter("miles");
            String xiuc = request.getParameter("xiuc");

            entity = peijianService.get(id);
            entity.setStatus(PeijianConts.STATUS_DOWN);
            entity.setDownDate(downDate);
            entity.setMiles(miles);
            entity.setXiuc(xiuc);

            peijianService.save(entity);
            JSONObject json = new JSONObject();
            json.element("success", 1);
            renderText(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 执行检修操作
     * @return
     */
    public String savemt() {
        try {
            Long id = Long.parseLong(request.getParameter("id"));
            String mtresult = request.getParameter("mtresult");

            entity = peijianService.get(id);
            entity.setStatus(PeijianConts.STATUS_MT);
            entity.setMtresult(mtresult);

            peijianService.save(entity);
            JSONObject json = new JSONObject();
            json.element("success", 1);
            renderText(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 执行报废操作
     * @return
     */
    public String savescrap() {
        try {
            Long id = Long.parseLong(request.getParameter("id"));
            String reason = request.getParameter("reason");

            entity = peijianService.get(id);
            entity.setStatus(PeijianConts.STATUS_SCRAP);
            entity.setReason(reason);

            peijianService.save(entity);
            JSONObject json = new JSONObject();
            json.element("success", 1);
            renderText(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 重新入库
     * @return
     */
    public String gook() {
        try {
            Long id = Long.parseLong(request.getParameter("id"));
            entity = peijianService.get(id);
            entity.setStatus(PeijianConts.STATUS_OK);
            peijianService.save(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private String buildOp(Accessory acce) {
        StringBuilder sb = new StringBuilder();
        sb.append("<div style='width: 130px;align:center;'>");
        sb.append("&nbsp;&nbsp;<a class='probebutton' href='javascript:del(" + acce.getId() + ");'>删除</a>");
        if (acce.getStatus() == PeijianConts.STATUS_OK) {
            sb.append("&nbsp;&nbsp;<a class='probebutton' href='javascript:goup(" + acce.getId() + ");'>上车</a>");
        } else if (acce.getStatus() == PeijianConts.STATUS_ON) {
            sb.append("&nbsp;&nbsp;<a class='probebutton' href='javascript:godown(" + acce.getId() + ");'>下车</a>");
        } else if (acce.getStatus() == PeijianConts.STATUS_DOWN) {
            sb.append("&nbsp;&nbsp;<a class='probebutton' href='javascript:gomt(" + acce.getId() + ");'>检修</a>");
        } else if (acce.getStatus() == PeijianConts.STATUS_MT) {
            sb.append("&nbsp;&nbsp;<a class='probebutton' href='javascript:gook(" + acce.getId() + ");'>入库</a>");
            sb.append("&nbsp;&nbsp;<a class='probebutton' href='javascript:goscrap(" + acce.getId() + ");'>报废</a>");
        }
        sb.append("</div>");

        return sb.toString();
    }

    private String buildStatus(Accessory acce) {
        StringBuilder sb = new StringBuilder();
        if (acce.getStatus() == PeijianConts.STATUS_OK) {
            sb.append("<span class='ok'>");
        } else if (acce.getStatus() == PeijianConts.STATUS_ON) {
            sb.append("<span class='on'>");
        } else if (acce.getStatus() == PeijianConts.STATUS_DOWN) {
            sb.append("<span class='down'>");
        } else if (acce.getStatus() == PeijianConts.STATUS_MT) {
            sb.append("<span class='mt'>");
        } else if (acce.getStatus() == PeijianConts.STATUS_SCRAP) {
            sb.append("<span class='scrap'>");
        }

        sb.append(status[acce.getStatus()]);
        sb.append("</span>");
        return sb.toString();
    }

    @Override
    public String input() throws Exception {
        return null;
    }

    public String common() {
        return "common";
    }

    public String goscrap() {
        Long id = Long.parseLong(request.getParameter("id"));

        request.setAttribute("id", id);
        request.setAttribute("acce", peijianService.get(id));
        return "scrap";
    }

    public String goup() {
        Long id = Long.parseLong(request.getParameter("id"));

        request.setAttribute("id", id);
        request.setAttribute("acce", peijianService.get(id));
        return "goup";
    }

    public String gomt() {
        Long id = Long.parseLong(request.getParameter("id"));

        request.setAttribute("id", id);
        request.setAttribute("acce", peijianService.get(id));
        return "mt";
    }

    public String godown() {

        Long id = Long.parseLong(request.getParameter("id"));

        request.setAttribute("id", id);
        request.setAttribute("acce", peijianService.get(id));
        return "godown";
    }

    @Override
    public String save() throws Exception {
        try {
            peijianService.save(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String delete() throws Exception {
        try {
            Long id = Long.parseLong(request.getParameter("id"));
            entity = peijianService.get(id);
            peijianService.delete(entity);

        } catch (Exception e) {
            logger.equals(e);
        }
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {
        if (id == null) {
            entity = new Accessory();
        } else {
            entity = peijianService.get(id);
        }

    }

}
